const dbConfig = require("../../../utils/dbConfig");

/** 
 * API
 */

// 获取首页数据
getHomeData = async (req, res) => {
  try {
    const data = await Promise.all(
      [
        getNumByCollege(),
        getOrderNum(),
        getTotalOrderNum(), 
        getRegisterNum(), 
        getTotalRegisterNum(),
        getMomentNum(),
        getAllMomentNum()
      ].map(p=>p.catch(e=>e))
      )
    let collegeNum = data[0]
    let orderNum = data[1]
    let totalOrderNum = data[2]
    let registerNum = data[3]
    let totalRegisterNum = data[4]
    let momentNum = data[5]
    let totalMomentNum = data[6]
    let collegeData = []
    let orderData = {}
    let registerData = {}
    let momentData = {}
    collegeNum.forEach(item => {
      collegeData.push({
        value: item.num,
        name: item.type
      })
    })
    orderData.todayCount = orderNum[0].todayCount
    orderData.totalCount = totalOrderNum[0].totalCount
    registerData.todayCount = registerNum[0].todayCount
    registerData.totalCount = totalRegisterNum[0].totalCount
    momentData.todayCount = momentNum[0].todayCount
    momentData.totalCount = totalMomentNum[0].totalCount
    res.send({
      code: 200,
      data: {
        collegeData,
        orderData,
        registerData,
        momentData
      }
    })
  } catch (e) {
    console.log(e)
    res.send({
      code: 500,
      message: "服务器出错了"
    })
  }
}


/**
 * function
 */
// 获取当日和总校友圈数量
getMomentNum = () => {
  let today = new Date()
  let time = (new Date(today.toDateString())).getTime()
  let sql = 'select count(*) as todayCount from moment where time between ? and ?'
  let sqlArr = [time.toString(), (time + 86400000).toString()]
  return dbConfig.SySqlConnect(sql, sqlArr)
}
getAllMomentNum = () => {
  sql = 'select count(*) as totalCount from moment'
  return dbConfig.SySqlConnect(sql, [])
}

//获取各分院注册人数
getNumByCollege = () => {
  let sql = 'select college as type,count(college) as num from user group by college'
  return dbConfig.SySqlConnect(sql, [])
}

// 获取当日数量
getOrderNum = () => {
  let today = new Date()
  let time = (new Date(today.toDateString())).getTime()
  let sql = 'select count(*) as todayCount from user_order where create_time between ? and ?'
  let sqlArr = [time.toString(), (time + 86400000).toString()]
  return dbConfig.SySqlConnect(sql, sqlArr)
}

// 获取总订单数量
getTotalOrderNum = () => {
  sql = 'select count(*) as totalCount from user_order'
  sqlArr = []
  return dbConfig.SySqlConnect(sql, sqlArr)
}

// 获取当日注册人数
getRegisterNum = () => {
  let today = new Date()
  let time = (new Date(today.toDateString())).getTime()
  let sql = 'select count(*) as todayCount from user where createTime between ? and ?'
  let sqlArr = [time.toString(), (time + 86400000).toString()]
  return dbConfig.SySqlConnect(sql, sqlArr)
}

// 获取总注册人数
getTotalRegisterNum = () => {
  sql = 'select count(*) as totalCount from user'
  return dbConfig.SySqlConnect(sql, [])
}

module.exports = {
  getHomeData
};